package com.terra;

import java.net.URL;
import java.util.Hashtable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.google.android.maps.GeoPoint;

public class MyCacheHandler extends DefaultHandler {

	Boolean currentElement = false;
	String currentValue = null;
	int currentIndex = -1;
	Boolean gotWpt = false;
	Boolean gotExtensions = false;
	String strPrefix;
	TCOverlayItem TCOverlay;
	MapItemizedOverlay thisCacheOverlay;
	
    Hashtable<String, Integer> table;
    
    public MyCacheHandler() {
    	Log.d("Debug", "Creating hash table");
    	table = new Hashtable<String, Integer>();
	    table.put(":name", 0);
	    table.put(":desc", 1);
	    table.put(":type", 2);
	    table.put(":link", 3);
	    table.put("terra:style", 4);
	    table.put("terra:size", 5);
	    table.put("terra:tps_points", 6);
	    table.put("terra:mce_score", 7);
	    table.put("terra:physical_challenge", 8);
	    table.put("terra:mental_challenge", 9);
	    table.put("terra:camo_challenge", 10);
	    table.put("terra:description", 11);
	    table.put("terra:hint", 12);
	    table.put(":metadata", 13);
	    table.put(":wpt", 14);
	    
	    table.put("groundspeak:type", 4);
	    table.put("groundspeak:container", 5);
	    table.put("groundspeak:terrain", 8);
	    table.put("groundspeak:difficulty", 10);
	    table.put("groundspeak:long_description", 11);
	    table.put("groundspeak:encoded_hints", 12);
	    
	    strPrefix = ":";
	    
	    Log.d("Debug", "Done creating hash table");
    }
    

	public void LoadCaches(String fileName, MapItemizedOverlay CacheOverlay) {
		try {
			thisCacheOverlay = CacheOverlay;
			
			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL("file://"+fileName);
//			"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");

			//Log.d("Debug", "Starting parse");
			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			//myCaches = new MyCacheHandler();
			//Log.d("Debug", "Parse done");
			xr.setContentHandler(this);
			xr.parse(new InputSource(sourceUrl.openStream()));
			

			} catch (Exception e) {
				Log.v("Debug", "XML Pasing Exception = " + e);
				  //AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
				  //dialog.setTitle("Error");
				  //dialog.setMessage("Error parsing " + fileName + "?");
				  //dialog.show();
				  Globals.strLastFile = "";
				  return;
			}	
	}
	
	public void startPrefixMapping(String prefix,
            String uri)
     throws SAXException {
		strPrefix = prefix + ":";
		//Log.d("Debug", "Starting prefix mapping <"+strPrefix+">");
	}	
	
		public void endPrefixMapping(java.lang.String prefix)
        throws org.xml.sax.SAXException {
			strPrefix = ":";
			//Log.d("Debug", "ending prefix mapping "+prefix);
	}
     
	/** Called when tag starts ( ex:- <name>AndroidPeople</name>
	* -- <name> )*/
	@Override
	public void startElement(String uri, String localName, String qName,
	Attributes attributes) throws SAXException {
	
		//Log.d("Debug", "Element started "+localName);
		currentElement = true;
		
		if (localName.equals("wpt") && strPrefix.equals(":") ) {
			/** Get attribute value */
			gotWpt = true;
			//Log.d("Debug", "Starting new overlay"+localName);
			String lat = attributes.getValue("lat");
			String lon = attributes.getValue("lon");			
			//itemizedoverlay.setPosition(lat, lon);
			int nLat = (int) (Double.parseDouble(lat) * 1e6);
			int nLon = (int) (Double.parseDouble(lon) * 1e6);
			GeoPoint point = new GeoPoint(nLat, nLon);
			TCOverlay = new TCOverlayItem(point, "", "");
			TCOverlay.setPosition(lat, lon);
			gotWpt = true;
		}else if (localName.equals("link") && gotWpt ) {
			String link = attributes.getValue("href");
			//Log.d("Debug", "Setting link <"+link+">");
			TCOverlay.setLink(link);				
		}
	
	}
	
	/** Called when tag closing ( ex:- <name>AndroidPeople</name>
	* -- </name> )*/
	@Override
	public void endElement(String uri, String localName, String qName)
	throws SAXException {
		
		//Log.d("Debug", "End element -> "+localName);
		currentElement = false;
		
		currentIndex = -1;
	    
		String localNameExtended = strPrefix + localName;
				
		try {
			currentIndex = (Integer)table.get(localNameExtended);
		}catch (NullPointerException e) {
			//Log.d("Debug", "Null pointer exception for element not found");
			currentIndex = -1;
		}
		
		//Log.d("Debug", "Getting index for <" + localNameExtended+"> : "+currentIndex +" gotWpt -> "+gotWpt);
		
		if( gotWpt ) {
			switch( currentIndex ) {
			case 0:
				TCOverlay.setID(currentValue);
				//Log.d("Debug", "Setting ID <" + currentValue +">");
				break;
				
			case 1:
				TCOverlay.setDesc(currentValue);
				//Log.d("Debug", "Setting desc <" + currentValue +">");
				break;
			
			case 2:
			case 3:
				
				break;
				
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
			case 11:
				//Log.d("Debug", "Index set but not used for <" + localNameExtended + "> value <" + currentValue +">" );
				break;
			
			case 13:
				Log.d("Debug", "Clearing cach overlays");
				//cachesList = new TerraCaches();
				break;
				
			case 14:
				thisCacheOverlay.addOverlay(TCOverlay, TCOverlay.getLink());
				//Log.d("Debug", "Adding overlay item: count -> "+thisCacheOverlay.size());
				gotWpt = false;
				break;
				
			default:
				//Log.d("Debug", "Index not used " + currentIndex );
			}
		}
		currentIndex = -1;
	}
	
	/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
	* -- to get AndroidPeople Character ) */
	@Override
	public void characters(char[] ch, int start, int length)
	throws SAXException {
	
			if (currentElement) {
			currentValue = new String(ch, start, length);
			//Log.d("Debug", "characters -> " + currentValue);
			currentElement = false;
		}
	}
}
